close all;clear all;clc;
% Parameters
A = 1.1;
g = 2;
lambda = 0.5;
eta = 1;
gprime = 0.1;
k = 0.5;

% Functions
tau_with_m = @ (g, gprime, lambda, eta, A, k, m)...
    max(1/(g-gprime)*(log(A)...
    - log((exp((g-gprime)*k*eta) - 1)/((g-gprime)*eta)...
    - exp((g-gprime)*k*eta)*(1-exp(-g*m))/(g*eta)...
    + (1-k+m/eta)*(g/lambda*exp((g-lambda)*(k*eta-m)-gprime*k*eta)...
    - (g/lambda-1)*exp((g-gprime)*k*eta-g*m)))),0);
alpha_with_m = @(g,gprime,eta,A,k,tau,m)...
    (A*exp(gprime*(tau+k*eta)) - exp(g*tau)*(exp(g*k*eta)-exp(gprime*k*eta))/((g-gprime)*eta)...
    + exp(g*tau)*(exp(g*k*eta)-exp(g*(k*eta-m)))/(g*eta))/(1-k+m/eta);

% Calculations
m = 0:0.001:k*eta;

for i = 1:length(m)
    taum(i) = max(tau_with_m(g,gprime,lambda,eta,A,k,m(i)),0);
    alpham(i) = alpha_with_m(g,gprime,eta,A,k,taum(i),m(i));
    hm(i) = lambda*exp(lambda*(k*eta-m(i)))/(exp(lambda*(k*eta-m(i)))-1);
    
    decomp1_h(i) = 1/g*log(hm(i)/(hm(i)-g));
    decomp2_alpha(i) = 1/g*log(alpham(i)*exp(-g*(k*eta-m(i))));
    
    diff(i) = taum(i) - (decomp1_h(i)+decomp2_alpha(i));
end

% Points for figures
for j = 1:length(m)
    if (j==1)|(j==length(m))|(mod(j,30)==0)
        decomp1_h_figure(j) = decomp1_h(j);
        decomp2_alpha_figure(j) = decomp2_alpha(j);
    else
        decomp1_h_figure(j) = NaN;
        decomp2_alpha_figure(j) = NaN;
    end
end

% Figures
h = figure;
set(h, 'defaultLegendInterpreter','latex',...
    'defaultAxesTickLabelInterpreter','latex');
a = axes;
yyaxis left;
p1 = plot(m,taum,'k','linewidth',2);
hold on;
yl = ylim();
plot([k*eta-(eta-1/(g-lambda)) k*eta-(eta-1/(g-lambda))],...
    [yl(1)-0.01 tau_with_m(g, gprime, lambda, eta, A, k, k*eta-(eta-1/(g-lambda)))],...
    'k--', 'linewidth', 1);

set(a, 'XTick',[0 k*eta-(eta-1/(g-lambda)) k*eta],...
    'XTicklabel',{'$0$' '$m^{*}$' '$k\eta$'},...
    'xlim',[0 k*eta], 'YColor', 'k', 'linewidth' ,1,...
    'Fontsize', 16, 'ylim', [yl(1) yl(2)]);

yyaxis right;
p2 = plot(m,decomp2_alpha_figure,'-.k*','linewidth',2,'MarkerSize',8);
hold on;
p3 = plot(m,decomp1_h_figure,'-.ok','linewidth',2,'MarkerSize',8);
plot(m,decomp2_alpha,'-.k','linewidth',2,'MarkerSize',8);
plot(m,decomp1_h,'-.k','linewidth',2,'MarkerSize',8);
yl2 = ylim();

set(a, 'YColor', 'k');

xlabel('Clawback Window ($m$)', 'interpreter','latex');
legend1 = legend([p1 p2 p3], {'$\tau^{*}$',...
    '$\frac{1}{g}\log\left[\alpha(\tau^{*},k,m) e^{-g(k\eta-m)}\right]$',...
    '$\frac{1}{g}\log\left(\frac{h(k,m)}{h(k,m)-g}\right)$'});
set(legend1, 'Location', 'southeast');
    
%saveas(h, 'tau_decomp_m.eps');
    
    
    
    